package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import com.itheima.utils.AesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;

import static com.itheima.constant.MessageConstant.*;

@Service(version = "1.0", interfaceClass = LoginService.class)
@Transactional
public class LoginServiceImpl implements LoginService {
    @Autowired
    JedisPool jedisPool;
    @Resource
    MemberMapper memberMapper;

    @Override
    public Result login(String telephone, String validateCode) {
        /**
         * 1.查看验证码是否正确
         * 2.手机号是否存在，不存在 注册
         * 3.给前端返回一个标识（token），前端发送请求的时候携带这个标识
         * 4.根据这个标识去redis中找 写入cookie
         * 5.token写入redis value是会员的信息
         */
        //校验验证码
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String code = jedis.get("LOGIN_" + telephone);
            if (code == null || !code.equals(validateCode)) {
                return Result.fail(VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Member member = memberMapper.findMemberByPhone(telephone);
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberMapper.save(member);
        }
        long l = System.currentTimeMillis() + 24 * 3600 * 1000;
        String token = AesUtils.encrypt(telephone + "_" + l, "itheima$%^!");
        if (jedis != null) {
            jedis.setex("TOKEN_"+token,24*3600, JSON.toJSONString(member));
            jedis.close();
        }
        return Result.success(LOGIN_SUCCESS,token);
    }



    @Override
    public Result userInfo(String token) {
        String decrypt = AesUtils.decrypt(token, "itheima$%^!");
        String[] split = decrypt.split("_");
        String time = split[1];
        long parseLong = Long.parseLong(time);
        if (parseLong<= System.currentTimeMillis()){
            return Result.fail(LOGIN_FAIL);
        }
        Jedis jedis = jedisPool.getResource();
        String memberJSON = jedis.get("TOKEN_" + token);
        if (memberJSON==null){
            return Result.fail(LOGIN_FAIL);
        }
        return Result.success(LOGIN_SUCCESS,JSON.parseObject(memberJSON,Member.class));
    }
}
